<template>
  <div class="history-page">
    <div class="page-header">
      <h2>观看记录</h2>
      <div class="stats">
        共观看 {{ userStore.watchHistoryList.length }} 部影片
        <button v-if="userStore.watchHistoryList.length > 0" @click="clearAllHistory" class="clear-btn">
          清空记录
        </button>
      </div>
    </div>

    <div v-if="userStore.watchHistoryList.length === 0" class="empty-state">
      <div class="empty-icon">📺</div>
      <h3>暂无观看记录</h3>
      <p>观看影片后，记录将在这里显示</p>
      <router-link to="/" class="browse-btn">去浏览影片</router-link>
    </div>

    <div v-else class="history-list">
      <div 
        v-for="item in userStore.watchHistoryList" 
        :key="item.id" 
        class="history-item"
        @click="$router.push(`/movie/${item.movieId}`)"
      >
        <div class="movie-poster">
          <img :src="item.movieCover" :alt="item.movieTitle" @error="handleImageError">
        </div>
        <div class="movie-info">
          <h3 class="movie-title">{{ item.movieTitle }}</h3>
          <p class="watch-time">观看时间: {{ formatTime(item.timestamp) }}</p>
          <div class="movie-meta">
            <span class="year">上映时间：{{ item.year }}</span>
            <span class="rating" v-if="getUserRating(item.movieId)">
              我的评分: {{ getUserRating(item.movieId).rating }}分
            </span>
          </div>
          <div class="actions">
            <button @click.stop="removeFromHistory(item.id)" class="action-btn remove">
              删除记录
            </button>
            <button @click.stop="continueWatching(item.movieId)" class="action-btn continue">
              继续观看
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useUserStore } from '../store/user';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';

const userStore = useUserStore();
const router = useRouter();

const handleImageError = (event) => {
  event.target.src = 'https://via.placeholder.com/300x450/2d3748/4a5568?text=No+Image';
};

const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;
  
  if (diff < 60000) return '刚刚';
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`;
  
  return date.toLocaleDateString('zh-CN');
};

const getUserRating = (movieId) => {
  return userStore.userRatings[movieId];
};

const removeFromHistory = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条观看记录吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'history-confirm-dialog'
      }
    );
    
    await userStore.removeFromWatchHistory(id);
    ElMessage.success('删除成功');
  } catch (error) {
    // 用户取消操作
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'));
    } else {
      ElMessage.info('已取消删除');
    }
  }
};

const clearAllHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有观看记录吗？此操作不可恢复。',
      '清空确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'history-confirm-dialog',
        confirmButtonClass: 'clear-confirm-btn'
      }
    );
    
    userStore.clearWatchHistory();
    ElMessage.success('清空成功');
  } catch (error) {
    // 用户取消操作
    ElMessage.info('已取消清空');
  }
};

const continueWatching = (movieId) => {
  router.push(`/play/${movieId}`);
};
</script>

<style scoped>
.history-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.stats {
  display: flex;
  align-items: center;
  gap: 16px;
  color: var(--muted);
}

.clear-btn {
  background: #e53e3e;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--muted);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-state h3 {
  margin-bottom: 10px;
  color: var(--text);
}

.browse-btn {
  display: inline-block;
  margin-top: 20px;
  padding: 10px 20px;
  background: var(--primary);
  color: white;
  text-decoration: none;
  border-radius: 6px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.history-item {
  display: flex;
  gap: 16px;
  background: var(--card);
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.history-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.movie-poster {
  flex-shrink: 0;
  width: 80px;
  height: 120px;
}

.movie-poster img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.movie-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.movie-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text);
  margin: 0;
}

.watch-time {
  color: var(--muted);
  font-size: 14px;
  margin: 0;
}

.movie-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 14px;
  color: var(--muted);
  line-height: 1.5;
}

.rating {
  color: #fbbf24;
  display: flex;
  align-items: center;
  gap: 4px;
}

.actions {
  display: flex;
  gap: 8px;
  margin-top: auto;
}

.action-btn {
  padding: 6px 12px;
  border: 1px solid #2d3748;
  border-radius: 4px;
  background: transparent;
  color: var(--text);
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
}

.action-btn.remove {
  border-color: #e53e3e;
  color: #e53e3e;
}

.action-btn.remove:hover {
  background: #e53e3e;
  color: white;
}

.action-btn.continue {
  border-color: var(--primary);
  color: var(--primary);
}

.action-btn.continue:hover {
  background: var(--primary);
  color: white;
}

@media (max-width: 768px) {
  .history-page {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .history-item {
    flex-direction: column;
  }
  
  .movie-poster {
    width: 100%;
    height: 200px;
  }
  
  .actions {
    justify-content: center;
  }
}

/* Element UI 确认对话框样式调整 */
:deep(.history-confirm-dialog) {
  .el-message-box {
    background: var(--card);
    border: 1px solid #2d3748;
    border-radius: 8px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
  }
  
  .el-message-box__header {
    border-bottom: 1px solid #2d3748;
    padding: 16px 20px;
  }
  
  .el-message-box__title {
    color: var(--text);
    font-weight: 600;
  }
  
  .el-message-box__content {
    padding: 20px;
    color: var(--muted);
  }
  
  .el-message-box__btns {
    border-top: 1px solid #2d3748;
    padding: 16px 20px;
  }
  
  .el-button {
    border-radius: 6px;
    font-weight: 500;
  }
  
  .el-button--primary {
    background: var(--primary);
    border-color: var(--primary);
  }
  
  .el-button--primary:hover {
    background: var(--primary-hover);
    border-color: var(--primary-hover);
  }
  
  .el-button--default {
    background: #2d3748;
    border-color: #4a5568;
    color: var(--text);
  }
  
  .el-button--default:hover {
    background: #4a5568;
    border-color: #718096;
  }
}

:deep(.clear-confirm-btn) {
  background: #e53e3e !important;
  border-color: #e53e3e !important;
}

:deep(.clear-confirm-btn:hover) {
  background: #c53030 !important;
  border-color: #c53030 !important;
}
</style>